#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: xjx
@time: 2023/11/27 18:20 
@file: where_vehicle.py
@project: nanchangproject
@describe: 判断车辆所属地区
"""
import sys
import os
import django
import requests
import json

sys.path.append('../../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nanchangproject.settings')
django.setup()  # 很关键的配置，必须先setup在导入models类
from drivinginfo.models import Drivinginfo, BasicInfo
from django.db.models import Avg


def where_vehicle(vin: str):
    my_data = Drivinginfo.objects.filter(vin=vin)[:30000]
    lng_mean = my_data.aggregate(Avg('longitude'))
    lng_mean_result = lng_mean['longitude__avg']
    lat_mean = my_data.aggregate(Avg('latitude'))
    lat_mean_result = lat_mean['latitude__avg']
    ak = 'GVbEaqlIMpwjYmXhvaamzieXhYIqBLB3'
    randius = 1000
    baiduUrl = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=%s&extensions_poi=1&radius=%s&output=json&coordtype=wgs84ll&location=%s,%s" % (
        ak, randius, lat_mean_result, lng_mean_result)
    req = requests.get(baiduUrl)
    baiduAddr = json.loads(req.text)
    province = baiduAddr["result"]["addressComponent"]["province"]  # 省份
    city = baiduAddr["result"]["addressComponent"]["city"]  # 城市
    this_vin = BasicInfo.objects.get(vin=vin)
    this_vin.province = province
    this_vin.city = city
    this_vin.save()
    print(f'平均经度：{lng_mean_result}，平均纬度：{lat_mean_result}，省份：{province}，城市：{city}')


def where_vehicle_list():
    vin_list = BasicInfo.objects.filter(province__isnull=True).values_list('vin')  # 筛选省份为空的vin
    # < QuerySet[('LETYBEG23MH043111',), ('LETYBEG23NH000292',), ('LETYBEG27LH039366',)] >
    for i in vin_list:
        where_vehicle(vin=i[0])


def home_info():
    all_data_count = Drivinginfo.objects.all().count()  # 统计总数据量
    vehicle_count = BasicInfo.objects.all().count()  # 总汽车数
    china_provinces = [
        "北京市", "天津市", "河北省", "山西省", "内蒙古自治区",
        "辽宁省", "吉林省", "黑龙江省", "上海市", "江苏省",
        "浙江省", "安徽省", "福建省", "江西省", "山东省",
        "河南省", "湖北省", "湖南省", "广东省", "广西壮族自治区",
        "海南省", "重庆市", "四川省", "贵州省", "云南省",
        "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏回族自治区",
        "新疆维吾尔自治区", "台湾省", "香港特别行政区", "澳门特别行政区"
    ]
    find_list = {}
    for province in china_provinces:
        this_province_count = BasicInfo.objects.filter(province=province).count()
        if this_province_count > 0:
            find_list[province] = this_province_count
    data = {
        '总数据量': all_data_count,
        '总汽车数': vehicle_count,
        '省份统计': find_list
    }
    print(data)
    # 计算总和
    total = sum(find_list[d] for d in find_list)
    # 计算每个省份的百分比并排序
    sorted_data = dict(sorted(find_list.items(), key=lambda item: item[1],reverse=True))
    # 计算总和
    total = sum(sorted_data.values())
    # 计算百分比并存储到新的字典中
    percentage_data = {province: (value / total) * 100 for province, value in sorted_data.items()}
    print(percentage_data)


if __name__ == '__main__':
    # where_vehicle_list()
    home_info()
